const exp = require('express');
const router = exp.Router();
const db = require('../db/db');
const kit = require('../kit/session');
const _ = require('../libs/global');

var ret = db.list('users', x=>x.id > 1);

router.post('/login', (req, res)=>{
    var data = req.body;
    var account = data.account;
    var password = data.password;
    _.verify(account, "accountNotFound");
    _.verify(password, 'passwordNotFound');
    
    var user = db.get("users", x=>{
        return x.account == account;
    })
    _.verify(user != null, "userNotFound");
    _.verify(user.password == password, "userNotFound");
    res.json({stat:"ok", session:kit.createSession(user), user:user});
})

router.post('/check', (req, res)=>{
    var data = req.body;
    var token = data.token;
    var s = kit.getSession(token);

    _.verify(s != null, "tokenExpired");
    var user = db.get('users', x => x.id == s.user);
    res.json({stat:"ok", session:s, user:user}); 
})

router.post('/logout', (req, res)=>{
    var data = req.body;
    var token = data.token;
    _.verify(kit.destorySession(token), "sessionNotFound");
    res.json({stat:"ok"});
})

router.post('/regist', (req, res)=>{
    var data = req.body;
    var account = data.account;
    var password = data.password;
    var nick = data.nick;
    _.verify(account, "accountNotFound");
    _.verify(password, 'passwordNotFound');
    _.verify(nick, 'nickNotFound');

    var s = db.get('users', x=>x.account == account);
    _.verify(s == null, 'accountExists');

    var user = db.add('users', {account:account, password:password, nick:nick});
    res.json({stat:"ok", user:user, session:kit.createSession(user)});
})

module.exports = router;